package com.wwg.threadSort;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @author: wwg
 * @date: 2022/3/11 17:46
 */


/**
 * CyclicBarrier控制线程顺序执行
 */
public class ThreadSortCyclicBarrier {

    private static final CyclicBarrier cyclicBarrier1 = new CyclicBarrier(2);
    private static final CyclicBarrier cyclicBarrier2 = new CyclicBarrier(2);

    public static void main(String[] args) {
        final Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println(Thread.currentThread().getName() + "执行");
                    cyclicBarrier1.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        }, "t1");

        final Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    cyclicBarrier1.await();
                    System.out.println(Thread.currentThread().getName() + "执行");
                    cyclicBarrier2.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        }, "t2");

        Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    cyclicBarrier2.await();
                    System.out.println(Thread.currentThread().getName() + "执行");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        }, "t3");

        thread3.start();
        thread1.start();
        thread2.start();
    }
}
